<template>
  <div id="app">
    <el-row :gutter="20" style="height: 100%">
      <!-- 左侧部门树 -->
      <el-col v-show="isShow" :span="4" :xs="24" style="height: 100%">
        <ContentWrap class="h-full">
          <MaterialTree
            ref="materialTreeRef"
            :show-checkbox="showTreeCheckbox"
            :typeInfo="typeInfo"
            @node-click="handleNodeClick"
            @check="handleTreeCheck"
          />
        </ContentWrap>
      </el-col>
      <el-col :span="20" :xs="24" style="height: 100%">
        <!-- 标签页和搜索工作栏 -->
        <ContentWrap>
          <el-tabs v-model="activeTab">
            <el-tab-pane :label="`全部(${totalCount})`" name="all" />
            <el-tab-pane
              v-for="type in QUESTION_TYPE_CONFIG"
              :key="type.type"
              :label="`${type.label}(${typeCountMap[type.type] || 0})`"
              :name="type.type"
            />
          </el-tabs>

          <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px">
            <el-form-item label="题目" prop="content">
              <el-input v-model="queryParams.content" placeholder="请输入题目名称" />
            </el-form-item>
            <el-form-item label="题目难度" prop="difficulty">
              <el-select v-model="queryParams.difficulty" class="!w-240px" clearable>
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.QUESTION_DIFFICULTY)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
              <el-button plain type="primary" @click="handleAdd">
                <Icon class="mr-5px" icon="ep:plus" />
                新增题目
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap class="h-full-list">
          <TreeToggleButton v-model:isShow="isShow" />
          <el-table
            ref="questionTableRef"
            v-loading="loading"
            :data="list"
            :show-overflow-tooltip="true"
            :stripe="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column v-if="showTableCheckbox" align="center" type="selection" width="55" />
            <el-table-column align="left" label="题目" prop="content" />
            <el-table-column align="center" label="题型" prop="type">
              <template #default="scope">
                {{ getQuestionTypeLabel(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="题库分类" prop="questionType" />
            <el-table-column align="center" label="难度" prop="difficulty">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.QUESTION_DIFFICULTY" :value="scope.row.difficulty" />
              </template>
            </el-table-column>
            <el-table-column
              :formatter="dateFormatter"
              align="center"
              label="创建时间"
              prop="createTime"
              width="180px"
            />
            <el-table-column align="center" label="操作" min-width="120px">
              <template #default="scope">
                <el-button link type="primary" @click="openForm('update', scope.row.id)">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </ContentWrap>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import MaterialTree from '../compont/TypeTree.vue'
import { dateFormatter } from '@/utils/formatTime'
import * as QuestionApi from '@/api/material/question'
import { QUESTION_TYPE_CONFIG, QuestionType } from '@/api/material/question'
import { computed, defineEmits, defineProps, nextTick, onMounted, reactive, ref, watch } from 'vue'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useQuestionStore } from '@/store/modules/material/question'
import TreeToggleButton from '@/components/TreeToggleButton/index.vue'
import { examPaperStore } from '@/store/modules/exam/paper'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'

const loading = ref(true) // 列表的加载中
const isShow = ref(true) // 列表的加载中
const list = ref<[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const typeInfo = ref({
  typeName: '题库分类',
  type: 2
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  content: undefined,
  type: undefined,
  questionType: undefined,
  difficulty: undefined,
  materialId: undefined as number | undefined,
  materialIds: [] as number[]
})
const queryFormRef = ref() // 搜索的表单
const activeTab = ref('all')

// 修改类型统计相关的响应式变量
const typeCountMap = ref<Record<string, number>>({})
// 修改 totalCount 的计算方式，直接使用 typeCountMap 中的 all 字段
const totalCount = computed(() => typeCountMap.value?.all || 0)

const questionStore = useQuestionStore()

const paperStore = examPaperStore()
const { fixedQuestions } = storeToRefs(paperStore)

// 定义props
const props = defineProps({
  showTreeCheckbox: {
    type: Boolean,
    default: false
  },
  showTableCheckbox: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['selection-change'])

// 确保导入所需的依赖
const route = useRoute()

/** 查询列表 */
const getList = async () => {
  try {
    const params = {
      ...queryParams
    }

    loading.value = true
    const data = await QuestionApi.getQuestionPage(params)
    list.value = data.list
    total.value = data.total

    // 获取当前页面已选中的题目
    const pageSelections = list.value.filter((item) =>
      fixedQuestions.value.some((selected) => selected.id === item.id)
    )

    // 设置表格的选中状态
    nextTick(() => {
      pageSelections.forEach((row) => {
        if (questionTableRef.value) {
          questionTableRef.value.toggleRowSelection(row, true)
        }
      })
    })
  } finally {
    loading.value = false
  }
}

/** 获取题型数量统计 */
const getTypeCount = async () => {
  try {
    const params = {
      content: queryParams.content,
      questionType: queryParams.questionType,
      difficulty: queryParams.difficulty,
      materialId: queryParams.materialId,
      materialIds: queryParams.materialIds,
      showTreeCheckbox: props.showTreeCheckbox
    }
    const data = await QuestionApi.getTypeCount(params)
    typeCountMap.value = data
  } catch (error) {
    console.error('获取题型数量失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  try {
    queryParams.pageNo = 1
    await getList()
  } catch (error) {
    console.error('查询失败：', error)
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.materialIds = []
  if (materialTreeRef.value) {
    materialTreeRef.value.value?.setCheckedKeys([])
  }
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  // 先清空所有数据
  questionStore.resetAllData()

  // 然后跳转到表单页面
  router.push({
    path: '/material/question/form',
    query: {
      type: type,
      id: id?.toString()
    }
  })
}

/** 跳转到新增题目 */
const handleAdd = () => {
  // 先清空所有数据
  questionStore.resetAllData()

  console.log('跳转到新增题目')
  router.push('/material/question/form')
}

/** 处理树节点点击 */
const handleNodeClick = async (id: number) => {
  if (props.showTreeCheckbox) {
    return
  }
  queryParams.materialId = id
  await handleQuery()
}

/** 初始化 **/
onMounted(async () => {
  await handleQuery()
})

// 获取题型标签
const getQuestionTypeLabel = (type: QuestionType) => {
  const config = QUESTION_TYPE_CONFIG.find((item) => item.type === type)
  return config?.label || '未知题型'
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('是否确认删除该题目?', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    await QuestionApi.deleteQuestion(id)
    ElMessage.success('删除成功')
    await handleQuery() // 刷新列表
  } catch (error) {
    // 用户取消删除或删除失败时不需要处理
  }
}

// 监听标签页变化
watch(activeTab, async (newVal: string) => {
  if (newVal === 'all') {
    queryParams.type = undefined
  } else {
    queryParams.type = newVal as QuestionType // 添加类型断言
  }
  await handleQuery()
})

// 处理表格选择变化
const handleSelectionChange = (selections) => {
  // 确保 selection 是数组
  if (!Array.isArray(selections)) {
    selections = []
  }

  // 获取当前页面中应该被选中的题目
  const pageSelections = list.value.filter((item) =>
    fixedQuestions.value.some((selected) => selected.id === item.id)
  )

  // 对比当前选中和之前选中的差异
  const newSelections = selections.filter(
    (item) => !pageSelections.some((pageItem) => pageItem.id === item.id)
  )
  const removedSelections = pageSelections.filter(
    (item) => !selections.some((selection) => selection.id === item.id)
  )

  // 更新 store 中的数据
  const updatedSelections = [
    ...fixedQuestions.value.filter(
      (item) => !removedSelections.some((removed) => removed.id === item.id)
    ),
    ...newSelections
  ]

  paperStore.setFixedQuestions(updatedSelections)

  console.log('当前选中的题目总数：', fixedQuestions.value.length)
}

// 修改表格引用的方式
const questionTableRef = ref(null)

// 修改 removeSelection 方法
const removeSelection = (item) => {
  if (!item) return
  console.log('removeSelection删除的题目：', item)
  if (questionTableRef.value) {
    // 通过 row 的 id 找到对应的行数据
    const row = list.value.find((item) => item.id === item.id)
    if (row) {
      questionTableRef.value.toggleRowSelection(row, false)
    }
  }
}

// 添加树形控件复选框选择处理函数
const handleTreeCheck = (data: {
  checkedKeys: number[]
  checkedNodes: any[]
  halfCheckedKeys: number[]
  halfCheckedNodes: any[]
}) => {
  // 更新 queryParams 中的 materialIds
  queryParams.materialIds = data.checkedKeys
  // 重新查询列表
  handleQuery()
  console.log('树形控件复选框选择处理函数:', data)
}

// 添加 MaterialTree 的引用
const materialTreeRef = ref()
// 修改 handleSelectQuestions 方法
const handleSelectQuestions = async () => {
  console.log('handleSelectQuestions')
  if (props.showTreeCheckbox) {
    try {
      const params = {
        content: queryParams.content,
        questionType: queryParams.questionType,
        difficulty: queryParams.difficulty,
        materialId: queryParams.materialId,
        materialIds: queryParams.materialIds,
        showTreeCheckbox: props.showTreeCheckbox
      }
      const data = await QuestionApi.getTypeAndQuestionCount(params)
      // 更新 store 中的题库列表
      paperStore.setRandomBanks(data)
    } catch (error) {
      console.error('获取题库统计失败:', error)
      ElMessage.error('获取题库统计失败')
      return
    }
  }

  emit('selection-change', fixedQuestions.value)
}

// 暴露方法和引用
defineExpose({
  removeSelection,
  questionTableRef,
  handleSelectQuestions
})
</script>

<style scoped>
#app {
  /* 删除固定高度和溢出设置 */
  /* height: 86vh; */
  /* overflow: auto; */
}

:deep(.el-pagination) {
  margin-top: 15px;
  justify-content: flex-end;
}

.upload-tips {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips div:first-child {
  margin-bottom: 2px;
}

/* 添加文件名输入框的样式 */
.filename-input :deep(.el-input__inner) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 修改上传组件中文件名的样式 */
:deep(.el-upload-list__item-name) {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 调整上传列表的宽度 */
:deep(.el-upload-list) {
  width: 100%;
}

/* 确保上传区域不会超出对话框 */
:deep(.el-upload-dragger) {
  width: 100%;
}

/* 调整对话框内容的最大宽度 */
:deep(.el-dialog__body) {
  max-width: 100%;
  overflow: hidden;
}

/* 确保选择框样式保留 */
:deep(.el-table .el-table__row .el-table-column--selection .cell) {
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

:deep(.el-table__header .el-table-column--selection .cell) {
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

:deep(.el-table__header .el-checkbox) {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  height: 100%;
}

:deep(.el-table__body .el-checkbox) {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  height: 100%;
}

:deep(.el-checkbox__inner) {
  position: relative;
  top: 0;
}

.h-full {
  height: calc(100vh - 150px); /* 使用视窗高度减去头部和其他元素的高度 */
  background-color: #ffffff; /* 或者你想要的其他颜色 */
}

.h-full-list {
  height: calc(100vh - 278px); /* 使用视窗高度减去头部和其他元素的高度 */
  background-color: #ffffff; /* 或者你想要的其他颜色 */
  overflow-y: auto;
}
</style>
